/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.gob.pnp.despachadores;

import java.awt.image.*;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
import javax.imageio.*;
import oracle.jdbc.*;
import pe.gob.pnp.actions.*;
import pe.gob.pnp.factories.*;

/**
 *
 * @author Eduardo Cavero Guzmán
 * @date 27/05/2010
 */

public class FolioDespachador {
    public static List<Folio> obtenerIdFoliosPorDocumento(int ndodiIdentificador) throws SQLException {
        List<Folio> lstIdFolios = new ArrayList<Folio>();
        Connection conn = null;
        try {
            conn = ConnectionPool.obtenerConexion();
            String sql = "{call SP_OBTENER_ID_FOLIOS_DOCDIGIT(?,?)}";
            CallableStatement cs = conn.prepareCall(sql);
            cs.setInt(1, ndodiIdentificador);
            cs.registerOutParameter(2, OracleTypes.CURSOR);
            cs.execute();
            ResultSet rs = (ResultSet) cs.getObject(2);
            int nroPagina = 1;
            while (rs.next()) {
                Folio folio = new Folio();
                folio.setNfoliIdentificador(rs.getInt("NFOLI_IDENTIFICADOR"));
                folio.setNroPagina(nroPagina++);
                lstIdFolios.add(folio);
            }
        } finally {
            ConnectionPool.liberarConexion(conn);
        }
        return lstIdFolios;
    }

    public static BufferedImage obtenerStreamFolio(int nfoliIdentificador) throws SQLException {
        BufferedImage imagen = null;
        Connection conn = null;
        try {
            conn = ConnectionPool.obtenerConexion();
            String sql = "{call SP_OBTENER_IMAGEN_FOLIO(?,?)}";
            CallableStatement cs = conn.prepareCall(sql);
            cs.setInt(1, nfoliIdentificador);
            cs.registerOutParameter(2, OracleTypes.CURSOR);
            cs.execute();
            ResultSet rs = (ResultSet) cs.getObject(2);
            InputStream in = null;
            if(rs.next()) {
                in = rs.getBinaryStream("BFOLI_IMAGEN");
                imagen = ImageIO.read(in);
            }
        } catch (IOException ex){
            throw new SQLException(ex);
        } finally {
            ConnectionPool.liberarConexion(conn);
        }
        return imagen;
    }
}
